package chapter20.question1;

import java.io.*;
import java.util.Arrays;

public class sortTxt {
    public static void main(String arg) throws IOException {
        // Check if source file does not exists
        File sourceFile = new File(arg);
        if (!sourceFile.exists()) {
            System.out.println("Source file " + arg
                    + " does not exist");
            System.exit(1);
        }

        try (
                // Create an input stream
                BufferedInputStream input =
                        new BufferedInputStream(new FileInputStream(sourceFile));
        ) {
            // read word from source file
            byte[] bytes = new byte[Math.toIntExact(sourceFile.length())];
            input.read(bytes);
            //save all words to a String[]
            String[] sortString = new String(bytes).trim().split("\\s");
            Arrays.sort(sortString);


            System.out.println("The sorted string is :");
            //split newline character
            for (String s : sortString) {
                if (!(s.equals(""))) {
                    System.out.print(s + ",");
                }
            }
        }
    }
}
